package com.wbs.shop.nuby.view.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wbs.shop.nuby.R;
import com.wbs.shop.nuby.api.ApiHelper;
import com.wbs.shop.nuby.api.RxHelper;
import com.wbs.shop.nuby.api.RxSubscribe;
import com.wbs.shop.nuby.bean.EmployeeBean;
import com.wbs.shop.nuby.bean.GoodsShowBean;
import com.wbs.shop.nuby.bean.PayModeBean;
import com.wbs.shop.nuby.bean.ShopMemberBean;
import com.wbs.shop.nuby.bean.UnderLineOrderBean;
import com.wbs.shop.nuby.commom.Key;
import com.wbs.shop.nuby.helper.FullyLinearLayoutManager;
import com.wbs.shop.nuby.utils.DOMStorageUtils;
import com.wbs.shop.nuby.utils.Logger;
import com.wbs.shop.nuby.utils.StringUtils;
import com.wbs.shop.nuby.utils.Utils;
import com.wbs.shop.nuby.view.activity.CashierActivityPadActivity;
import com.wbs.shop.nuby.view.activity.SelectEmployeeActivity;
import com.wbs.shop.nuby.view.adapter.GoodsShowAdapter;
import com.wbs.shop.nuby.view.adapter.PayModeAdapter;
import com.wbs.shop.nuby.view.dialog.CashierPayShowDialog;
import com.wbs.shop.nuby.widget.InputEditText;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import io.reactivex.Observable;
import library.qrcode.zxing.QrCodeHelper;
import library.qrcode.zxing.QrCodeListener;

public class CashierPayFragment extends com.wbs.shop.nuby.view.base.BaseFragment {
    private static final String IS_PAD = "IS_PAD";

    public static CashierPayFragment newInstance(boolean isPad) {
        CashierPayFragment cashierPayFragment = new CashierPayFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(IS_PAD, isPad);
        cashierPayFragment.setArguments(bundle);
        return cashierPayFragment;
    }

    private static final String[] WX = new String[]{"10", "11", "12", "13", "14", "15"};
    private static final String[] ALI = new String[]{"25", "26", "27", "28", "29", "30"};
    public static final int REQUEST_CODE_EMPLOYEE = 2;
    @BindView(R.id.rv_order)
    RecyclerView rvOrder;
    @BindView(R.id.member_phone)
    InputEditText etMemberPhone;
    @BindView(R.id.etReduction)
    InputEditText etReduction;
    @BindView(R.id.member_name)
    TextView memberName;
    @BindView(R.id.ll_member_name)
    LinearLayout llMemberName;
    @BindView(R.id.rv_pay_mode)
    RecyclerView rvPayMode;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tvEmployee)
    TextView tvEmployee;
    private PayModeAdapter mPayModeAdapter;
    private GoodsShowAdapter mGoodsShowAdapter;
    private PayModeBean payModeBean;
    private UnderLineOrderBean mUnderLineOrderBean;
    private EmployeeBean mEmployeeBean;
    private String clientPayAmount;// 客户端计算金额
    private String payAmount;
    private String offLineDerateVprice;
    private String authCode;
    private String pinfo;
    private ShopMemberBean mShopMemberBean;
    private boolean isPad = false;
    private boolean isPhoneChange = false;

    @Override
    protected int tellMeLayout() {
        return R.layout.fragment_cashier_pay;
    }

    @Override
    public void init(View view, Bundle savedInstanceState) {
        mPayModeAdapter = new PayModeAdapter(getContext());
        ArrayList<PayModeBean> payModeBeanList = new ArrayList<>();
        payModeBeanList.add(new PayModeBean(R.mipmap.icon_scan, getString(R.string.text_cashier_pay_scan), PayModeBean.PAY_MODE_WX, true));
//        payModeBeanList.add(new PayModeBean(R.mipmap.alipay, getString(R.string.text_cashier_pay_alpay), PayModeBean.PAY_MODE_ALPAY));
        payModeBeanList.add(new PayModeBean(R.mipmap.balance, getString(R.string.text_cashier_pay_balance), PayModeBean.PAY_MODE_BALANCE));
        payModeBeanList.add(new PayModeBean(R.mipmap.in_cash, getString(R.string.text_cashier_pay_money), PayModeBean.PAY_MODE_MONEY));
        payModeBeanList.add(new PayModeBean(R.mipmap.credit_card, getString(R.string.text_cashier_pay_card), PayModeBean.PAY_MODE_CARD));
        mPayModeAdapter.setDatas(payModeBeanList);
        rvPayMode.setLayoutManager(new FullyLinearLayoutManager(getContext()));
        rvPayMode.setAdapter(mPayModeAdapter);
        ((DefaultItemAnimator) rvPayMode.getItemAnimator()).setSupportsChangeAnimations(false);
        mGoodsShowAdapter = new GoodsShowAdapter(getContext());
        rvOrder.setLayoutManager(new FullyLinearLayoutManager(getContext()));
        rvOrder.setAdapter(mGoodsShowAdapter);
        if (hasExtras()) {
            isPad = getArguments().getBoolean(IS_PAD, false);
        }
        etReduction.switchDelay(true, s -> {
            offLineDerateVprice = s.toString();
            if (offLineDerateVprice.endsWith(".")) {
                offLineDerateVprice = offLineDerateVprice.replace(".", "");
            }
            loadUserInfo();
        });
        if (getActivity() != null &&
                getActivity().getIntent() != null &&
                getActivity().getIntent().getExtras() != null &&
                getActivity().getIntent().getExtras().containsKey(Key.GOODS_SHOW)) {
            changeGoods(getActivity().getIntent().getParcelableArrayListExtra(Key.GOODS_SHOW), getActivity().getIntent().getStringExtra(Key.PAY_AMOUNT));
        }
    }

    public void changeGoods(List<GoodsShowBean> goodsShowBeans, String payAmount) {
        if (mGoodsShowAdapter != null) {
            this.clientPayAmount = payAmount;
            this.payAmount = payAmount;
            mGoodsShowAdapter.setDatas(goodsShowBeans);
            mGoodsShowAdapter.notifyDataSetChanged();
            pinfo = JSON.toJSONString(goodsShowBeans);
            if (loadUserInfo()) {
                tvMoney.setText(getString(R.string.text_money, payAmount));
            }
        }
    }

    @OnTextChanged(value = R.id.member_phone, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void afterTextChanged(Editable e) {
        isPhoneChange = true;
        loadUserInfo();
    }

    private boolean loadUserInfo() {
        if (etMemberPhone.length() == 11) {
            if (isPhoneChange) {
                ApiHelper.getApiService().regAccount(etMemberPhone.getText().toString(), DOMStorageUtils.getLocal("sid"))
                        .compose(RxHelper.handleResult(this))
                        .subscribe(new RxSubscribe<ShopMemberBean>() {
                            @Override
                            protected void _onNext(ShopMemberBean shopMemberBean) {
                                mShopMemberBean = shopMemberBean;
                                mGoodsShowAdapter.changeDiscount(mShopMemberBean.getDiscount());
                                if (getActivity() instanceof CashierActivityPadActivity) {
                                    ((CashierActivityPadActivity) getActivity()).changeDiscount(mShopMemberBean.getDiscount());
                                }
                            }
                        });
            }
            ApiHelper.getApiService().buyOrderForOffLine(etMemberPhone.getText().toString(), 1, mEmployeeBean != null ? mEmployeeBean.getId() : null, offLineDerateVprice, pinfo)
                    .compose(RxHelper.handleResult(this))
                    .subscribe(new RxSubscribe<UnderLineOrderBean>(getContext()) {
                        @Override
                        protected void _onNext(UnderLineOrderBean underLineOrderBean) {
                            mUnderLineOrderBean = null;
                            payAmount = underLineOrderBean.getPayAmount();
                            tvMoney.setText(getString(R.string.text_money, payAmount));
                            memberName.setText(StringUtils.defaultIfEmpty(underLineOrderBean.getNickname(), getString(R.string.text_anonymous)));
                            llMemberName.setVisibility(View.VISIBLE);
                            mPayModeAdapter.getItem(mPayModeAdapter.getItemCount() - 3).setSubName(getString(R.string.text_money, underLineOrderBean.getBalance()));
                            mPayModeAdapter.notifyItemChanged(mPayModeAdapter.getItemCount() - 3);
                        }
                    });

            return false;
        } else {
            mGoodsShowAdapter.changeDiscount(1);
//            if (getActivity() instanceof CashierActivityPadActivity) {
//                ((CashierActivityPadActivity) getActivity()).changeDiscount(1);
//            }
        }
        isPhoneChange = false;
        return true;
    }

    @OnClick({R.id.pay, R.id.tvEmployee})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvEmployee:
                if (isPad) {
                    ((CashierActivityPadActivity) getActivity()).openEmployee();
                } else
                    goActicityForResult(SelectEmployeeActivity.class, REQUEST_CODE_EMPLOYEE);
                break;
            case R.id.tvConfirm:
                doPay();
                break;
            case R.id.pay:
                if (mGoodsShowAdapter.getItemCount() <= 0) {
                    Utils.toastMessageLong("请先选择商品");
                    return;
                }
//                if (etMemberPhone.getText().length() != 11) {
//                    Utils.toastMessageLong("请输入正确手机号码");
//                    return;
//                }
                payModeBean = mPayModeAdapter.getCheck();
                if (payModeBean == null) {
                    Utils.toastMessageLong("请选择支付方式");
                    return;
                }
                if (PayModeBean.PAY_MODE_MONEY == payModeBean.getPaymode()) {
                    new CashierPayShowDialog(getContext(), Utils.isPad(), payAmount, this::onViewClicked).show();
                } else if (PayModeBean.PAY_MODE_WX == payModeBean.getPaymode() || PayModeBean.PAY_MODE_ALPAY == payModeBean.getPaymode()) {// 如果是微信或者支付宝，则先打开扫一扫
                    openQrCode(result -> {
                        try {
                            if (StringUtils.isNumber(result)) {// 验证是否为数字
                                //微信规则：用户刷卡条形码规则：18位纯数字，以10、11、12、13、14、15开头
                                if (result.length() == 18 && StringUtils.startsWith(result, WX)) {
                                    authCode = result;
                                    mPayModeAdapter.changCheckByPayMode(PayModeBean.PAY_MODE_WX);
                                    doPay();
                                    //支付宝规则：支付授权码，25~30开头的长度为16~24位的数字，实际字符串长度以开发者获取的付款码长度为准
                                } else if (result.length() >= 16 && result.length() <= 24 && StringUtils.startsWith(result, ALI)) {
                                    authCode = result;
                                    mPayModeAdapter.changCheckByPayMode(PayModeBean.PAY_MODE_ALPAY);
                                    doPay();
                                } else {
                                    Utils.toastMessageLong("无法识别的二维码");
                                }
                            } else {
                                Utils.toastMessageLong("无法识别的二维码");
                            }
                        } catch (Exception e) {
                            Logger.e(e);
                        }
                    });
                } else {
                    doPay();
                }
                break;
        }
    }

    private void doPay() {
        payModeBean = mPayModeAdapter.getCheck();
        Observable.just("")
                .flatMap(s -> {
                    if (mUnderLineOrderBean == null) {
                        return ApiHelper.getApiService().buyOrderForOffLine(StringUtils.defaultIfEmpty(etMemberPhone.getText().toString(), "10000000000"), 0, mEmployeeBean != null ? mEmployeeBean.getId() : null, etReduction.getText().toString(), pinfo)
                                .compose(RxHelper.onlyHandleResult()).doOnNext(underLineOrderBean -> mUnderLineOrderBean = underLineOrderBean);
                    }
                    return Observable.just(mUnderLineOrderBean);
                })
                .flatMap(underLineOrderBean -> ApiHelper.getApiService().payUnderLineOrder(underLineOrderBean.getPayCode(), authCode, payModeBean.getPaymode()))
                .compose(RxHelper.handleResult(this))
                .subscribe(new RxSubscribe<JSONObject>(getContext()) {
                    @Override
                    protected void _onNext(JSONObject jsonObject) {
                        mUnderLineOrderBean = null;
                        if (jsonObject.containsKey("msg"))
                            Utils.toastMessageLong(jsonObject.getString("msg"));
                        if (isPad) {
                            etMemberPhone.setText("");
                            memberName.setText("");
                            llMemberName.setVisibility(View.GONE);
                            mPayModeAdapter.getItem(mPayModeAdapter.getItemCount() - 3).setSubName(getString(R.string.text_money, "0"));
                            mPayModeAdapter.notifyItemChanged(mPayModeAdapter.getItemCount() - 3);
                            mEmployeeBean = null;
                            tvEmployee.setText("");
                            etReduction.setText("");
                            ((CashierActivityPadActivity) getActivity()).clearCart();
                        } else {
                            getActivity().setResult(Activity.RESULT_OK);
                            getActivity().finish();
                        }
                    }
                }.setCancelable(false));
    }

    private void openQrCode(QrCodeListener qrCodeListener) {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CAMERA)
                .onGranted(permissions -> doOpenQrCode(qrCodeListener))
                .onDenied(permissions -> doOpenQrCode(qrCodeListener))
                .start();
    }

    private void doOpenQrCode(QrCodeListener qrCodeListener) {
        QrCodeHelper.scan(getActivity(), qrCodeListener);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE_EMPLOYEE == requestCode && resultCode == Activity.RESULT_OK && data != null) {
            mEmployeeBean = (EmployeeBean) data.getSerializableExtra("employee");
            tvEmployee.setText(StringUtils.defaultIfEmpty(mEmployeeBean.getUserName(), ""));
        }
    }
}
